package DataStructure.tree.practice;

import DataStructure.tree.TreeNode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;

/**
 * 199. 二叉树的右视图
 */
public class RightSideView {

    /**
     * 思路：层序遍历，每层获取最后一个节点
     */
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null) return result;
        ArrayDeque<TreeNode> deque = new ArrayDeque<>();
        deque.add(root);
        while (!deque.isEmpty()) {
            //一次while循环中出队一层的节点，入队下一层的节点
            int levelSize = deque.size();
            for (int i = 1;i <= levelSize;i++) {
                TreeNode node = deque.remove();
                if (i == levelSize) result.add(node.val);
                if (node.left != null) deque.add(node.left);
                if (node.right != null) deque.add(node.right);
            }
        }
        return result;
    }
}
